<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import axios from 'axios'
import { isLoggedIn } from '../utils/auth.js'
import { showToast, showConfirmDialog } from 'vant'

const route = useRoute()
const router = useRouter()
const orderType = ref(route.query.type || 'all')

const tabs = [
  { key: 'all', label: '全部订单' },
  { key: 'pending_payment', label: '待支付' },
  { key: 'pending_travel', label: '已支付' },
  { key: 'pending_review', label: '待点评' },
  { key: 'refunds', label: '退款单' }
]

const loading = ref(false)
const allOrders = ref([])
const errorMessage = ref('')

const statusLabels = {
  0: '待支付',
  1: '已支付',
  2: '已取消',
  3: '已完成'
}

const statusFilters = {
  all: () => true,
  pending_payment: (order) => order.status === 0,
  pending_travel: (order) => order.status === 1,
  pending_review: (order) => order.status === 3,
  refunds: (order) => order.refund_status && order.refund_status !== 0
}

const filteredOrders = computed(() => {
  const filterFn = statusFilters[orderType.value] || statusFilters.all
  return allOrders.value
    .filter(filterFn)
    .slice()
    .sort((a, b) => {
      const ta = a?.create_time ? new Date(a.create_time).getTime() : 0
      const tb = b?.create_time ? new Date(b.create_time).getTime() : 0
      return tb - ta
    })
})

const payingOrderNo = ref('')
const deletingOrderId = ref(null)

const canDeleteOrder = (order) => {
  if (!order) return false
  const deletableStatuses = [0, 1, 2, 3]
  return deletableStatuses.includes(order.status)
}

const getPaymentSubject = (order) => {
  if (order.product_type === 'hotel' && order.hotel_name) {
    return `酒店订单 - ${order.hotel_name}`
  }
  if (order.product_type === 'ticket' && order.ticket_name) {
    return `门票订单 - ${order.ticket_name}`
  }
  return '订单支付'
}

const goToPay = async (order) => {
  if (!order?.order_no) {
    showToast('订单信息不完整，无法支付')
    return
  }

  if (payingOrderNo.value) return
  payingOrderNo.value = order.order_no

  const query = {
    order_no: order.order_no
  }

  if (order.product_type === 'hotel') {
    if (order.product_id) query.hotel_id = order.product_id
    if (order.room_type_id) query.room_type_id = order.room_type_id
  }

  if (order.check_in_date) query.check_in_date = order.check_in_date
  if (order.check_out_date) query.check_out_date = order.check_out_date
  if (order.rooms) query.rooms = order.rooms
  if (order.guest_name) query.guest_name = order.guest_name
  if (order.phone) query.phone = order.phone

  try {
    await router.push({
      path: '/payment',
      query
    })
  } catch (error) {
    console.error('跳转支付页失败:', error)
    showToast('跳转支付页面失败，请稍后重试')
  } finally {
    payingOrderNo.value = ''
  }
}

const confirmDelete = (order) => {
  if (!order?.id) {
    showToast('订单信息不完整，无法删除')
    return
  }

  showConfirmDialog({
    title: '删除订单确认',
    message: '确定要删除该订单吗？删除后不可恢复。',
    confirmButtonText: '确认删除',
    cancelButtonText: '取消'
  })
    .then(() => {
      deleteOrder(order)
    })
    .catch(() => {})
}

const deleteOrder = async (order) => {
  if (deletingOrderId.value) return

  deletingOrderId.value = order.id
  try {
    const response = await axios.get('http://localhost:8000/orders/delete', {
      params: { order_id: order.id }
    })

    if (response.data?.code === 200) {
      showToast('订单删除成功')
      allOrders.value = allOrders.value.filter((item) => item.id !== order.id)
    } else {
      const message = response.data?.message || '删除订单失败'
      showToast(message)
    }
  } catch (error) {
    console.error('删除订单失败:', error)
    const message = error?.response?.data?.message || error.message || '删除订单失败'
    showToast(message)
  } finally {
    deletingOrderId.value = null
  }
}

onMounted(() => {
  if (!isLoggedIn()) {
    showToast('请先登录')
    return
  }
  loadOrders()
})

const loadOrders = async () => {
  const userId = localStorage.getItem('user_id')
  if (!userId) {
    showToast('未获取到用户信息，请重新登录')
    return
  }

  try {
    loading.value = true
    errorMessage.value = ''
    const response = await axios.get('http://localhost:8000/orders/getall', {
      params: { user_id: userId }
    })

    const list = Array.isArray(response.data?.data) ? response.data.data : []
    allOrders.value = list.map((order) => ({
      ...order,
      status_text: statusLabels[order.status] || '未知状态',
      date_range: formatDateRange(order.check_in_date, order.check_out_date),
      created_at_text: formatDate(order.create_time),
      amount_text: formatAmount(order.amount),
      refund_text: formatRefundStatus(order.refund_status)
    }))
  } catch (error) {
    console.error('加载订单失败:', error)
    errorMessage.value = error?.response?.data?.message || error.message || '加载订单失败'
    showToast(errorMessage.value)
  } finally {
    loading.value = false
  }
}

const switchTab = (tab) => {
  orderType.value = tab.key
}

const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  if (Number.isNaN(date.getTime())) return dateStr
  return date.toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' })
}

const formatDateRange = (start, end) => {
  const startDate = formatDate(start)
  const endDate = formatDate(end)
  if (startDate && endDate) return `${startDate} - ${endDate}`
  return startDate || endDate || ''
}

const formatAmount = (amount) => {
  const number = Number(amount)
  if (Number.isNaN(number)) return '¥0.00'
  return `¥${number.toFixed(2)}`
}

const formatRefundStatus = (status) => {
  if (status === 1) return '退款申请中'
  if (status === 2) return '已退款'
  return ''
}
</script>

<template>
  <div class="orders-page">
    <div class="page-header">
      <h1 class="page-title">我的订单</h1>
    </div>
    
    <div class="tabs-container">
      <div
        v-for="tab in tabs"
        :key="tab.key"
        :class="['tab-item', { active: orderType === tab.key }]"
        @click="switchTab(tab)"
      >
        {{ tab.label }}
      </div>
    </div>

    <div class="orders-list">
      <div v-if="loading" class="loading-state">
        <div class="spinner"></div>
        <div class="loading-text">正在加载订单...</div>
      </div>
      <div v-else-if="errorMessage" class="error-state">
        <div class="error-icon">⚠️</div>
        <div class="error-text">{{ errorMessage }}</div>
      </div>
      <div v-else-if="filteredOrders.length === 0" class="empty-state">
        <div class="empty-icon">📋</div>
        <div class="empty-text">暂无订单</div>
      </div>
      <div v-else>
        <div v-for="order in filteredOrders" :key="order.id" class="order-item">
          <div class="order-header">
            <div class="order-title">
              <span class="order-type">{{ order.product_type === 'hotel' ? '酒店订单' : order.product_type === 'ticket' ? '门票订单' : '旅行订单' }}</span>
              <span class="order-no">订单号：{{ order.order_no }}</span>
            </div>
            <div class="order-status">{{ order.status_text }}</div>
          </div>

          <div class="order-body">
            <div class="order-row">
              <span class="label">出行时间</span>
              <span class="value">{{ order.date_range || '待定' }}</span>
            </div>
            <div class="order-row">
              <span class="label">金额</span>
              <span class="value amount">{{ order.amount_text }}</span>
            </div>
            <div class="order-row" v-if="order.refund_text">
              <span class="label">退款状态</span>
              <span class="value refund">{{ order.refund_text }}</span>
            </div>
          </div>

          <div class="order-footer">
            <span class="created-time">下单时间：{{ order.created_at_text || '未知' }}</span>
            <div class="action-buttons" v-if="canDeleteOrder(order) || order.status === 0">
              <button
                v-if="canDeleteOrder(order)"
                class="delete-btn"
                type="button"
                :disabled="deletingOrderId === order.id"
                @click="confirmDelete(order)"
              >
                {{ deletingOrderId === order.id ? '删除中...' : '删除订单' }}
              </button>
              <button
                v-if="order.status === 0"
                class="pay-btn"
                type="button"
                :disabled="payingOrderNo === order.order_no"
                @click="goToPay(order)"
              >
                {{ payingOrderNo === order.order_no ? '跳转中...' : '去支付' }}
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.orders-page {
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: 100px;
}

.page-header {
  background: white;
  padding: 16px;
  border-bottom: 1px solid #e8e8e8;
}

.page-title {
  font-size: 20px;
  font-weight: 600;
  color: #333;
}

.tabs-container {
  background: white;
  display: flex;
  overflow-x: auto;
  border-bottom: 1px solid #e8e8e8;
  padding: 0 16px;
}

.tab-item {
  padding: 12px 20px;
  font-size: 14px;
  color: #666;
  white-space: nowrap;
  cursor: pointer;
  border-bottom: 2px solid transparent;
  transition: all 0.2s;
}

.tab-item.active {
  color: #1890ff;
  border-bottom-color: #1890ff;
  font-weight: 600;
}

.orders-list {
  padding: 16px;
}

.loading-state,
.empty-state,
.error-state {
  text-align: center;
  padding: 80px 20px;
}

.spinner {
  width: 40px;
  height: 40px;
  margin: 0 auto 16px auto;
  border: 4px solid rgba(0, 0, 0, 0.05);
  border-top: 4px solid #1890ff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

.empty-icon,
.error-icon {
  font-size: 64px;
  margin-bottom: 16px;
  opacity: 0.3;
}

.loading-text,
.empty-text,
.error-text {
  font-size: 16px;
  color: #999;
}

.error-text {
  color: #ff4d4f;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.order-item {
  background: white;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.order-title {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.order-type {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.order-no {
  font-size: 12px;
  color: #999;
}

.order-status {
  font-size: 14px;
  color: #1890ff;
  font-weight: 600;
}

.order-body {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.order-row {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
  color: #666;
}

.order-row .label {
  color: #999;
}

.order-row .value.amount {
  color: #ff7a45;
  font-weight: 600;
}

.order-row .value.refund {
  color: #ff4d4f;
}

.order-footer {
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid #f0f0f0;
  font-size: 12px;
  color: #999;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.pay-btn {
  background: #ff6b35;
  color: #fff;
  border: none;
  border-radius: 16px;
  padding: 6px 16px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: background 0.2s ease;
}

.action-buttons {
  display: flex;
  align-items: center;
  gap: 12px;
}

.delete-btn {
  background: #f0f0f0;
  color: #666;
  border: none;
  border-radius: 16px;
  padding: 6px 16px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
}

.pay-btn:hover:not(:disabled) {
  background: #ff8557;
}

.pay-btn:disabled {
  background: #d9d9d9;
  cursor: not-allowed;
}

.delete-btn:hover:not(:disabled) {
  background: #ffecec;
  color: #ff4d4f;
}

.delete-btn:disabled {
  background: #d9d9d9;
  color: #aaa;
  cursor: not-allowed;
}
</style>

